package com.kx.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName MybatisUtils
 * @Description
 * @Author sun
 * @Date 2021/5/13 13:51
 * @Version 1.0
 **/
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    static {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static SqlSession getSqlSession() {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    public static <T> T getMapper(Class<T> tClass) {
        return getSqlSession().getMapper(tClass);
    }

    public static void commit() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.commit();
            close();
        }
    }

    public static void rollback() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.rollback();
            close();
        }
    }

    public static void close() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            threadLocal.remove();
            sqlSession.close();
        }
    }

}
